package com.study.modules.saas.service;

import com.qcloud.cos.COSClient;
import com.qcloud.cos.model.ObjectMetadata;
import com.qcloud.cos.model.PutObjectRequest;
import com.qcloud.cos.model.PutObjectResult;
import com.study.common.BusinessException;
import com.study.config.CosConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;

/**
 * @Author hupengming
 * @ClassName
 * @Date 2022-10-19 14:24
 * @Version 1.0
 */
@Slf4j
@Service
public class CosService {


    @Autowired
    private COSClient client;

    @Autowired
    private CosConfig cosConfig;


    /**
     * 上传文件，将本地文件上传到cos
     *
     * @param key 图片key
     * @param file 文件
     */
    public String load(String key, MultipartFile file) {
        try{
            InputStream inputStream = file.getInputStream();
            ObjectMetadata objectMetadata = new ObjectMetadata();
            // 输入流上传必须设定contentLength，否则http客户端可能会缓存所有数据，存在内存OOM情况
            objectMetadata.setContentLength(inputStream.available());
            PutObjectRequest putObjectRequest = new PutObjectRequest(cosConfig.getBucketName(), key, inputStream, objectMetadata);
            PutObjectResult putObjectResult = client.putObject(putObjectRequest);
            log.info("putObjectResult:{}",putObjectResult);
            return getFileUrl(key);
        }catch (IOException e){
            throw new BusinessException(e.getMessage());
        }
    }

    public String getFileUrl(String cospath) {
        return String.format("https://%s.cos.%s.myqcloud.com/%s",
                cosConfig.getBucketName(), cosConfig.getRegion(), cospath);
    }

    /**
     * 删除cos图片
     *
     * @param key 图片key
     */
    public void delete(String key){
        client.deleteObject(cosConfig.getBucketName(),key);
    }

}
